package com.suisung.shopsuite.common.config.shire;

import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Value;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

import static com.suisung.shopsuite.common.utils.UploadUtil.getUploadBaseDir;

public class SecureStaticFilter extends AccessControlFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        // 防御1：仅允许GET方法
        if (!"GET".equalsIgnoreCase(httpRequest.getMethod())) {
            return false;
        }

        // 防御2：验证文件物理存在
        String requestPath = httpRequest.getServletPath();
        String filePath = getUploadBaseDir() + requestPath.replace("/front/sys/upload/", "");
        File targetFile = new File(filePath);

        // 防御3：防止目录遍历攻击
        if (!targetFile.getCanonicalPath().startsWith(new File(getUploadBaseDir()).getCanonicalPath())) {
            return false;
        }

        return targetFile.exists() && targetFile.isFile();
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        // 记录安全日志
        // SecurityLogger.logStaticAccessAttempt(request);
        sendRedirectToErrorPage(request, response);
        return false;
    }

    private void sendRedirectToErrorPage(ServletRequest request, ServletResponse response) throws IOException {
        WebUtils.issueRedirect(request, response, "/error/403");
    }
}